#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2023/3/2 11:30
# @Author  : WuJunQi
# @Email   : 1479652129@qq.com
# @File    : MainWindow.py
# @Software: PyCharm
import os
import queue
import sys
import threading
import time
from asyncio import Queue
from pathlib import Path
from random import random
import re
import cv2
from IPython.external.qt_for_kernel import QtCore
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent
from PyQt5.QtMultimediaWidgets import QVideoWidget
from PyQt5.QtWidgets import QMainWindow, QFileDialog, QLabel, QSizePolicy, QMessageBox

from Detect_Change_System.Detect_Change_System import Detect_Change_System
from benchmarks import FILE
from pyqt.MainWindow_qt import Ui_MainWindow
from pyqt.MyLabel import MyLabel
from pyqt.People import Peoples
from pyqt.yolov5_class import yolov5
from utils.general import print_args

ROOT = FILE.parents[0]  # YOLOv5 root directory
if str(ROOT) not in sys.path:
    sys.path.append(str(ROOT))  # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative

class MyMainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        # 继承于窗口类

        self.label = MyLabel(self.widget)
        # self.label.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)

        self.label.setPixmap(QPixmap("../data/images/QQ图片20230307191616.jpg").scaled(960, 540))
        self.label.setScaledContents(True)
        self.image_pattern = r'\.(jpg|png|gif|bmp|mp4|avi|mkv|mov)$'
        self.directory = ""
        self.queue = queue.Queue()
        self.myrunning = yolov5(self.directory)
        self.detectPeople = Peoples()
        self.detect_change_system = Detect_Change_System(self)
        self.startTimer(1)
    def openfile(self):
        # 其中self指向自身，"读取文件夹"为标题名，"./"为打开时候的当前路径
        directory = QFileDialog.getOpenFileName(self,"选取文件","./")  # 起始路径
        directory = directory[0]
        self.directory = directory
        if self.directory == "" or not re.search(self.image_pattern, self.directory):
            QMessageBox.warning(self, '警告', '您未设置视频路径或者文件并非可以检测的文件')
            return
        video_capture = cv2.VideoCapture(self.directory)
        success, image = video_capture.read()
        # 检查是否成功读取第一帧
        if success:
            # 显示第一帧图像
            rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            height, width, channels = rgb_image.shape
            bytes_per_line = channels * width
            qimage = QImage(rgb_image.data, width, height, bytes_per_line,QImage.Format_RGB888)
            # 将QImage对象转换为QPixmap对象
            qpixmap = QPixmap.fromImage(qimage)
            scaled_pixmap = qpixmap.scaled(960, 540, aspectRatioMode=QtCore.Qt.KeepAspectRatio)
            self.label.setPixmap(scaled_pixmap)
            self.label.four_point = []
            cv2.waitKey(0)
        else:
            print('Failed to read first frame.')
        return directory
    def run(self):
        print(re.search(self.image_pattern, self.directory))
        if self.directory == "" or re.search(self.image_pattern, self.directory) is None or len(self.label.four_point) != 4:
            QMessageBox.warning(self, '警告', '您未设置视频路径或者文件并非可以检测的文件')
            return
        t = threading.Thread(target=self.myrunning.main,args=(self.queue,self.directory,self))
        t.daemon = True
        t.start()
    def timerEvent(self, event):
        while self.queue.empty() is not True:
            qpixmap = self.queue.get()
            scaled_pixmap = qpixmap.scaled(960, 540, aspectRatioMode=QtCore.Qt.KeepAspectRatio)
            self.label.setPixmap(scaled_pixmap)
